package com.goldgov.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;

import com.mysql.fabric.xmlrpc.base.Data;
/** 
 * 日期处理类
 * @ClassName: DateUtil 
 * @Description: TODO
 */
public class DateUtil {
	private static final Log logger = LogFactory.getLog(DateUtil.class);  
	  
    public static final String YYYYMMDD = "yyyy-MM-dd";  
  
    public static final String YYYYMMDD_ZH = "yyyy年MM月dd日";  
  
    public static final int FIRST_DAY_OF_WEEK = Calendar.MONDAY; // 中国周一是一周的第一天  
  
    /** 
     *  
     * @param strDate 
     * @return 
     */  
    public static Date parseDate(String strDate) {  
        return parseDate(strDate, null);  
    }  
  
    /** 
     * parseDate 
     *  
     * @param strDate 
     * @param pattern 
     * @return 
     */  
    public static Date parseDate(String strDate, String pattern) {  
        Date date = null;  
        try {  
            if (pattern == null) {  
                pattern = YYYYMMDD;  
            }  
            SimpleDateFormat format = new SimpleDateFormat(pattern);  
            date = format.parse(strDate);  
        } catch (Exception e) {  
            logger.error("parseDate error:" + e);  
        }  
        return date;  
    }  
  
    /** 
     * format date 
     *  
     * @param date 
     * @return 
     */  
    public static String formatDate(Date date) {  
        return formatDate(date, null);  
    }  
  
    /** 
     * format date 
     *  
     * @param date 
     * @param pattern 
     * @return 
     */  
    public static String formatDate(Date date, String pattern) {  
        String strDate = null;  
        try {  
            if (pattern == null) {  
                pattern = YYYYMMDD;  
            }  
            SimpleDateFormat format = new SimpleDateFormat(pattern);  
            strDate = format.format(date);  
        } catch (Exception e) {  
            logger.error("formatDate error:", e);  
        }  
        return strDate;  
    }  
  
    /** 
     * 取得日期：年 
     *  
     * @param date 
     * @return 
     */  
    public static int getYear(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int year = c.get(Calendar.YEAR);  
        return year;  
    }  
  
    /** 
     * 取得日期：月 
     *  
     * @param date 
     * @return 
     */  
    public static int getMonth(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int month = c.get(Calendar.MONTH);  
        return month + 1;  
    }  
  
    /** 
     * 取得日期：日 
     *  
     * @param date 
     * @return 
     */  
    public static int getDay(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int da = c.get(Calendar.DAY_OF_MONTH);  
        return da;  
    }  
  
    /** 
     * 取得当天日期是周几 
     *  
     * @param date 
     * @return 
     */  
    public static int getWeekDay(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int week_of_year = c.get(Calendar.DAY_OF_WEEK);  
        return week_of_year - 1;  
    }  
  
    /** 
     * 取得一年的第几周 
     *  
     * @param date 
     * @return 
     */  
    public static int getWeekOfYear(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int week_of_year = c.get(Calendar.WEEK_OF_YEAR);  
        return week_of_year;  
    }  
  
    /** 
     * getWeekBeginAndEndDate 
     *  
     * @param date 
     * @param pattern 
     * @return 
     */  
    public static String getWeekBeginAndEndDate(Date date, String pattern) {  
        Date monday = getMondayOfWeek(date);  
        Date sunday = getSundayOfWeek(date);  
        return formatDate(monday, pattern) + " - "  
                + formatDate(sunday, pattern);  
    }  
  
    /** 
     * 根据日期取得对应周周一日期 
     *  
     * @param date 
     * @return 
     */  
    public static Date getMondayOfWeek(Date date) {  
        Calendar monday = Calendar.getInstance();  
        monday.setTime(date);  
        monday.setFirstDayOfWeek(FIRST_DAY_OF_WEEK);  
        monday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);  
        return monday.getTime();  
    }  
  
    /** 
     * 根据日期取得对应周周日日期 
     *  
     * @param date 
     * @return 
     */  
    public static Date getSundayOfWeek(Date date) {  
        Calendar sunday = Calendar.getInstance();  
        sunday.setTime(date);  
        sunday.setFirstDayOfWeek(FIRST_DAY_OF_WEEK);  
        sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);  
        return sunday.getTime();  
    }  
  
    /** 
     * 取得月的剩余天数 
     *  
     * @param date 
     * @return 
     */  
    public static int getRemainDayOfMonth(Date date) {  
        int dayOfMonth = getDayOfMonth(date);  
        int day = getPassDayOfMonth(date);  
        return dayOfMonth - day;  
    }  
  
    /** 
     * 取得月已经过的天数 
     *  
     * @param date 
     * @return 
     */  
    public static int getPassDayOfMonth(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        return c.get(Calendar.DAY_OF_MONTH);  
    }  
  
    /** 
     * 取得月天数 
     *  
     * @param date 
     * @return 
     */  
    public static int getDayOfMonth(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);  
    }  
  
    /** 
     * 取得月第一天 
     *  
     * @param date 
     * @return 
     */  
    public static Date getFirstDateOfMonth(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));  
        return c.getTime();  
    }  
  
    /** 
     * 取得月最后一天 
     *  
     * @param date 
     * @return 
     */  
    public static Date getLastDateOfMonth(Date date) {  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));  
        return c.getTime();  
    }  
  
    /** 
     * 取得季度第一天 
     *  
     * @param date 
     * @return 
     */  
    public static Date getFirstDateOfSeason(Date date) {  
        return getFirstDateOfMonth(getSeasonDate(date)[0]);  
    }  
  
    /** 
     * 取得季度最后一天 
     *  
     * @param date 
     * @return 
     */  
    public static Date getLastDateOfSeason(Date date) {  
        return getLastDateOfMonth(getSeasonDate(date)[2]);  
    }  
  
    /** 
     * 取得季度天数 
     *  
     * @param date 
     * @return 
     */  
    public static int getDayOfSeason(Date date) {  
        int day = 0;  
        Date[] seasonDates = getSeasonDate(date);  
        for (Date date2 : seasonDates) {  
            day += getDayOfMonth(date2);  
        }  
        return day;  
    }  
  
    /** 
     * 取得季度剩余天数 
     *  
     * @param date 
     * @return 
     */  
    public static int getRemainDayOfSeason(Date date) {  
        return getDayOfSeason(date) - getPassDayOfSeason(date);  
    }  
  
    /** 
     * 取得季度已过天数 
     *  
     * @param date 
     * @return 
     */  
    public static int getPassDayOfSeason(Date date) {  
        int day = 0;  
  
        Date[] seasonDates = getSeasonDate(date);  
  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int month = c.get(Calendar.MONTH);  
  
        if (month == Calendar.JANUARY || month == Calendar.APRIL  
                || month == Calendar.JULY || month == Calendar.OCTOBER) {// 季度第一个月  
            day = getPassDayOfMonth(seasonDates[0]);  
        } else if (month == Calendar.FEBRUARY || month == Calendar.MAY  
                || month == Calendar.AUGUST || month == Calendar.NOVEMBER) {// 季度第二个月  
            day = getDayOfMonth(seasonDates[0])  
                    + getPassDayOfMonth(seasonDates[1]);  
        } else if (month == Calendar.MARCH || month == Calendar.JUNE  
                || month == Calendar.SEPTEMBER || month == Calendar.DECEMBER) {// 季度第三个月  
            day = getDayOfMonth(seasonDates[0]) + getDayOfMonth(seasonDates[1])  
                    + getPassDayOfMonth(seasonDates[2]);  
        }  
        return day;  
    }  
  
    /** 
     * 取得季度月 
     *  
     * @param date 
     * @return 
     */  
    public static Date[] getSeasonDate(Date date) {  
        Date[] season = new Date[3];  
  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
  
        int nSeason = getSeason(date);  
        if (nSeason == 1) {// 第一季度  
            c.set(Calendar.MONTH, Calendar.JANUARY);  
            season[0] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.FEBRUARY);  
            season[1] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.MARCH);  
            season[2] = c.getTime();  
        } else if (nSeason == 2) {// 第二季度  
            c.set(Calendar.MONTH, Calendar.APRIL);  
            season[0] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.MAY);  
            season[1] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.JUNE);  
            season[2] = c.getTime();  
        } else if (nSeason == 3) {// 第三季度  
            c.set(Calendar.MONTH, Calendar.JULY);  
            season[0] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.AUGUST);  
            season[1] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.SEPTEMBER);  
            season[2] = c.getTime();  
        } else if (nSeason == 4) {// 第四季度  
            c.set(Calendar.MONTH, Calendar.OCTOBER);  
            season[0] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.NOVEMBER);  
            season[1] = c.getTime();  
            c.set(Calendar.MONTH, Calendar.DECEMBER);  
            season[2] = c.getTime();  
        }  
        return season;  
    }  
  
    /** 
     *  
     * 1 第一季度 2 第二季度 3 第三季度 4 第四季度 
     *  获取当前季度
     * @param date 
     * @return 
     */  
    public static int getSeason(Date date) {  
  
        int season = 0;  
  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int month = c.get(Calendar.MONTH);  
        switch (month) {  
        case Calendar.JANUARY:  
        case Calendar.FEBRUARY:  
        case Calendar.MARCH:  
            season = 1;  
            break;  
        case Calendar.APRIL:  
        case Calendar.MAY:  
        case Calendar.JUNE:  
            season = 2;  
            break;  
        case Calendar.JULY:  
        case Calendar.AUGUST:  
        case Calendar.SEPTEMBER:  
            season = 3;  
            break;  
        case Calendar.OCTOBER:  
        case Calendar.NOVEMBER:  
        case Calendar.DECEMBER:  
            season = 4;  
            break;  
        default:  
            break;  
        }  
        return season;  
    }  
  
    
    public static Date strToDate(String strDate) {
    	strDate=strDate.trim();
    	String dateFormat = "yyyy-MM-dd HH:mm:ss";
		String a1 = "[0-9]{4}[0-9]{2}[0-9]{2}[0-9]{2}[0-9]{2}[0-9]{2}";//yyyyMMddHHmmss
		String a2 = "[0-9]{4}[0-9]{2}[0-9]{2}";//yyyyMMdd
		String a6 = "[0-9]{4}[0-9]{2}";//yyyyMM
		String a3 = "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}";//yyyy-MM-dd HH:mm:ss
		String a4 = "[0-9]{4}-[0-9]{2}-[0-9]{2}";//yyyy-MM-dd
		String a5= "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}";//yyyy-MM-dd  HH:mm
		if(Pattern.compile(a1).matcher(strDate).matches()){
			dateFormat = "yyyyMMddHHmmss";
		}
		if(Pattern.compile(a2).matcher(strDate).matches()){
			dateFormat = "yyyyMMdd";
		}
		if(Pattern.compile(a6).matcher(strDate).matches()){
			dateFormat = "yyyyMM";
		}
		if(Pattern.compile(a3).matcher(strDate).matches()){
			dateFormat = "yyyy-MM-dd HH:mm:ss";
		}
		if(Pattern.compile(a4).matcher(strDate).matches()){
			dateFormat = "yyyy-MM-dd";
		}
		if(Pattern.compile(a5).matcher(strDate).matches()){
			dateFormat = "yyyy-MM-dd HH:mm";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = null;
		try {
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
    }
    
    /**
     * 把时间转换为指定格式
     * @date 2018年9月18日 下午5:11:51 
     * @author hanxiangyu
     * @param date
     * @return
     */
    public static String dateToStr(Date date) {
		String dateTimeStr = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar dateOne=Calendar.getInstance();
		dateOne.setTime(new Date());
		Calendar dateTwo=Calendar.getInstance();
		dateTwo.setTime(date);
		long timeOne=dateOne.getTimeInMillis();
		long timeTwo=dateTwo.getTimeInMillis();
		long difference = timeOne - timeTwo;
//		long day=difference/(3600*24*1000);//相差天数：   
		long hour=difference/(3600*1000);//相差小时：   
		long minute=difference/(60*1000);//相差分钟：   
//		long second=difference/1000 ;//相差秒：  
		if (minute <= 1) {
			dateTimeStr = "刚刚";
		}else if(minute > 1 && minute <= 60) {
			dateTimeStr = minute + "分钟前";
		}else if(minute > 60 && hour <= 24) {
			dateTimeStr = hour + "小时前";
		}else if(hour > 24) {
			dateTimeStr = sdf.format(date);
		}
		return dateTimeStr;
	}
    /**
     * 开始时间到结束时间一共有几个月
     * @param beginDate
     * @param endDate
     * @author liziwen
     * @return 月份个数
     */
    public static int monthNum(Date beginDate,Date endDate) {
    	Calendar calendarBegin=Calendar.getInstance();
    	calendarBegin.setTime(beginDate);
    	int i=1;
    	while (endDate.after(calendarBegin.getTime())) {
    		calendarBegin.add(Calendar.MONTH, 1);
			i++;
		}
    	return i;
    }
    /**
     * 两个日期之间共有多少个季度
     * @param beginDate
     * @param endDate
     * @author liziwen
     * @return 季度个数
     */
    public static int quarterNum(Date beginDate,Date endDate) {
    	Calendar calendarBegin=Calendar.getInstance();
    	calendarBegin.setTime(beginDate);
    	int i=1;
    	int quarter=getSeason(beginDate);//当前季度
    	while (endDate.after(calendarBegin.getTime())) {
    		calendarBegin.add(Calendar.MONTH, 1);
    		int theQuarter=getSeason(calendarBegin.getTime());
    		if(quarter!=theQuarter) {
    			quarter=theQuarter;
    			i++;
    		}
		}
    	return i;
    }
    
    
    public static String getTimeStr(String givingTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.ENGLISH);
		givingTime = givingTime.replaceAll("([^0-9] )|([^0-9])", " ");
		givingTime = givingTime.replaceAll("\\s{1,}", " ");
		String[] numbers = givingTime.split(" ");
		if (numbers.length == 1) {
			String time = numbers[0];
			SimpleDateFormat format;

			if (time.length() == 8)
				format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
			else if (time.length() == 14)
				format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);
			else if (time.length() > 8) {
				time = time.substring(0, 8);
				format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
			} else {
				format = null;
				return sdf.format(new Date(0));
			}
			Date date = null;
			try {
				date = format.parse(time);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			return sdf.format(date);
		}
		Vector<Integer> nums = new Vector<Integer>();
		for (int i = 0; i < 6; i++)
			nums.add(0);

		if (numbers.length > 3) {
			if (Integer.parseInt(numbers[2]) > 31) {
				String tmp = numbers[2].substring(0, 2);
				if (Integer.parseInt(tmp) > 31)
					tmp = numbers[2].substring(0, 1);
				numbers[3] = numbers[2].substring(tmp.length());
				numbers[2] = tmp;
			}
		}
		for (int i = 0; i < numbers.length; i++) {
			nums.setElementAt(Integer.parseInt(numbers[i]), i);
		}

		int year = nums.get(0);
		int month = nums.get(1);
		int day = nums.get(2);

		int hour = nums.get(3);
		if (hour > 24)
			hour = 0;
		int min = nums.get(4);
		if (min > 60)
			min = 0;
		int sec = nums.get(5);
		if (sec > 60)
			sec = 0;

		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month - 1, day, hour, min, sec);
		return sdf.format(calendar.getTime());
	}
	public static Date getTime(String givingTime) {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
//				Locale.ENGLISH);
		givingTime = givingTime.replaceAll("([^0-9] )|([^0-9])", " ");
		givingTime = givingTime.replaceAll("\\s{1,}", " ");
		String[] numbers = givingTime.split(" ");
		if (numbers.length == 1) {
			String time = numbers[0];
			SimpleDateFormat format;
			
			if (time.length() == 8)
				format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
			else if (time.length() == 14)
				format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);
			else if (time.length() > 8) {
				time = time.substring(0, 8);
				format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
			} else {
				format = null;
				return new Date(0);
			}
			Date date = null;
			try {
				date = format.parse(time);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			return date;
		}
		Vector<Integer> nums = new Vector<Integer>();
		for (int i = 0; i < 6; i++)
			nums.add(0);
		
		if (numbers.length > 3) {
			if (Integer.parseInt(numbers[2]) > 31) {
				String tmp = numbers[2].substring(0, 2);
				if (Integer.parseInt(tmp) > 31)
					tmp = numbers[2].substring(0, 1);
				numbers[3] = numbers[2].substring(tmp.length());
				numbers[2] = tmp;
			}
		}
		for (int i = 0; i < numbers.length; i++) {
			nums.setElementAt(Integer.parseInt(numbers[i]), i);
		}
		
		int year = nums.get(0);
		int month = nums.get(1);
		int day = nums.get(2);
		
		int hour = nums.get(3);
		if (hour > 24)
			hour = 0;
		int min = nums.get(4);
		if (min > 60)
			min = 0;
		int sec = nums.get(5);
		if (sec > 60)
			sec = 0;
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month - 1, day, hour, min, sec);
		return calendar.getTime();
	}
    
	/**
	 * 获取两个时间相差多少分钟
	 * @date 2018年10月30日 上午11:32:43 
	 * @author hanxiangyu
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getMinute(Date date1,Date date2) {
		Calendar dateOne = Calendar.getInstance();
		dateOne.setTime(date1);
		Calendar dateTwo = Calendar.getInstance();
		dateTwo.setTime(date2);
		long timeOne = dateOne.getTimeInMillis();
		long timeTwo = dateTwo.getTimeInMillis();
		long difference = timeOne - timeTwo;
		// long day=difference/(3600*24*1000);//相差天数：
		// long hour=difference/(3600*1000);//相差小时：
		long minute = difference / (60 * 1000);// 相差分钟：
		return minute;
	}
	
	/**
	 * 获取两个时间相差多少天
	 * @date 2018年10月30日 上午11:32:43 
	 * @author hanxiangyu
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDay(Date date1,Date date2) {
		Calendar dateOne = Calendar.getInstance();
		dateOne.setTime(date1);
		Calendar dateTwo = Calendar.getInstance();
		dateTwo.setTime(date2);
		long timeOne = dateOne.getTimeInMillis();
		long timeTwo = dateTwo.getTimeInMillis();
		long difference = timeOne - timeTwo;
		long day=difference/(3600*24*1000);//相差天数：
		if (day < 0) {
			day = Math.abs(day);
		}
		// long hour=difference/(3600*1000);//相差小时：
//		long minute = difference / (60 * 1000);// 相差分钟：
		return day;
	}
	
	
    
    
}
